/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.service.render.exporter;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.retabel.persistence.entity.document.ContentTypeEnum;
import org.retabel.persistence.entity.render.RenderedDocumentPart;
import org.retabel.persistence.entity.report.RenderingEngineEnum;
import org.retabel.service.render.RenderServiceException;
import org.retabel.service.render.exportable.ExportableDocumentPart;
import org.retabel.service.render.exportable.FopExportableDocumentPart;
import org.retabel.service.render.exportable.JasperReportsExportableDocumentPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import javax.xml.transform.*;
import javax.xml.transform.sax.SAXResult;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.*;

/**
 * Class description.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 21:45 16.10.11
 *
 * @author Peter Herber
 * @version 1.0
 */
public class FopRenderingEngine extends RenderingEngine {

    /** The Logger. */
    private static final Logger logger = LoggerFactory.getLogger(JasperReportsExportableDocumentPart.class);

    /** The filename of the user configuration xml within the report design package */
    private static final String USER_CONFIG_XML_FILENAME_IN_REPORT_DESIGN_PACKAGE = "userconfig.xml";

    private final Set<ContentTypeEnum> supportedContentTypeList;

    private final Set<ContentTypeEnum> supportedConcatenationTypeList;

    /** the report design base uri used as base uri to retrieve configuration and fonts from */
    private final URI reportDesignURI;

    /**
     * Create a new FOP rendering engine instance
     *
     * @param reportDesignURI the report design base uri used as base uri to retrieve configuration and fonts from
     */
    public FopRenderingEngine(URI reportDesignURI) {
        this.reportDesignURI = reportDesignURI;
        supportedContentTypeList = new HashSet<>();
        supportedContentTypeList.add(ContentTypeEnum.PDF);
        supportedContentTypeList.add(ContentTypeEnum.RTF);
        supportedConcatenationTypeList = new HashSet<>();
        supportedConcatenationTypeList.add(ContentTypeEnum.PDF);
    }

    @Override
    public Set<ContentTypeEnum> supportedContentTypes() {
        return Collections.unmodifiableSet(supportedContentTypeList);
    }

    @Override
    public Set<ContentTypeEnum> supportsConcatenationForContentTypes() {
        return Collections.unmodifiableSet(supportedConcatenationTypeList);
    }

    @Override
    public RenderedDocumentPart exportAndConcatenate(List<? extends ExportableDocumentPart> exportableDocumentParts,
                                                     ContentTypeEnum contentType) throws RenderServiceException {

        List<FopExportableDocumentPart> fopExportableDocumentParts = (List<FopExportableDocumentPart>) exportableDocumentParts;

        List<FopExportableDocumentPart> exportList = new LinkedList<>();
        for (FopExportableDocumentPart fopExportableDocumentPart : fopExportableDocumentParts) {
            if (!RenderingEngineEnum.FOP.equals(fopExportableDocumentPart.getRenderingEngine())) {
                throw new RenderServiceException(
                    "exportable document has wrong rendering engine, expected: " + RenderingEngineEnum.FOP + " found: "
                    + fopExportableDocumentPart.getRenderingEngine());
            }

            exportList.add(fopExportableDocumentPart);
        }

        // print each source

        try {
            byte[] bytes = exportAndConcatenate(contentType, exportList);

            logger.debug("Content size: {}", bytes.length);

            RenderedDocumentPart documentPart = new RenderedDocumentPart();
            documentPart.setContent(bytes);
            documentPart.setContentType(contentType);

            return documentPart;
        } catch (Exception e) {
            throw new RenderServiceException(e.getMessage(), e);
        }

    }

    private byte[] exportAndConcatenate(ContentTypeEnum contentType, List<FopExportableDocumentPart> exportList)
        throws RenderServiceException, TransformerException, IOException, SAXException {

        if (exportList == null || exportList.size() == 0) {
            throw new IllegalArgumentException("export list is null or empty!");
        }

        List<byte[]> exportedList = new LinkedList<>();

        for (FopExportableDocumentPart fopExportableDocumentPart : exportList) {

            String mimeType;
            switch (contentType) {
                case PDF:
                    mimeType = MimeConstants.MIME_PDF;
                    break;
                case RTF:
                    mimeType = MimeConstants.MIME_RTF;
                    break;
                default:
                    throw new RenderServiceException("No mime type for " + contentType + " found!");
            }

            FopFactory fopFactory = FopFactory.newInstance();

            String packageName =
                fopExportableDocumentPart.getSectionConfiguration().getReportDesign().getReportDesignPackage().getName();
            String packageVersion =
                fopExportableDocumentPart.getSectionConfiguration().getReportDesign().getReportDesignPackage().getVersion();

            URI designPackageURI = reportDesignURI.resolve(packageName + "/" + packageVersion + "/");

            fopFactory.setBaseURL(designPackageURI.toString());
            fopFactory.getFontManager().setFontBaseURL(designPackageURI.toString());

            // check if the userconfig.xml is available within the design pacakge, if so load it as fop user config
            if (fopExportableDocumentPart.getSectionConfiguration().getReportDesign().getReportDesignPackage()
                                         .getReportDesignByName(USER_CONFIG_XML_FILENAME_IN_REPORT_DESIGN_PACKAGE) != null) {
                logger.info("Report design package contains user configuration xml");

                URI userConfigURI = designPackageURI.resolve(USER_CONFIG_XML_FILENAME_IN_REPORT_DESIGN_PACKAGE);

                logger.info("Loading fop user config: "+userConfigURI);

                // load user config from report design package
                fopFactory.setUserConfig(userConfigURI.toString());
            }

            logger.info("fopFactory.getBaseURL: "+fopFactory.getBaseURL());
            logger.info("fopFactory.getFontBaseURL: "+fopFactory.getFontManager().getFontBaseURL());

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            Fop fop = fopFactory.newFop(mimeType, baos);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            transformer.setErrorListener(new ErrorListener() {
                @Override
                public void warning(TransformerException exception) throws TransformerException {
                    logger.error(exception.getMessage(), exception);
                }

                @Override
                public void error(TransformerException exception) throws TransformerException {
                    throw exception;
                }

                @Override
                public void fatalError(TransformerException exception) throws TransformerException {
                    throw exception;
                }
            });

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            transformer.transform(fopExportableDocumentPart.getRenderedContent(), res);

            exportedList.add(baos.toByteArray());
        }

        // join to a single rendered document if possible
        if (exportedList.size() > 1) {
            if (!supportedConcatenationTypeList.contains(contentType)) {
                throw new RenderServiceException("FOP doesn't support concatenation for content type '" + contentType + "'");
            }

            return concatenate(exportedList, contentType);
        }

        return exportedList.get(0);
    }

    private byte[] concatenate(List<byte[]> exportedList, ContentTypeEnum contentType) throws RenderServiceException {
        try {
            switch (contentType) {
                case PDF:
                    return concatPDFs(exportedList);
            }
            throw new RenderServiceException("No export type for " + contentType + " found!");

        } catch (Exception e) {
            throw new RenderServiceException(e.getMessage(), e);
        }
    }

}
